package com.apache;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread{
	private Socket socket;
	private InputStream is;
	private PrintStream out;
	private static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"WebRoot";
	private static final int BUFFER_SIZE = 1024;
	
	public Processor(Socket socket){
		this.socket = socket;
		try {
			is = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		String fileName = parse(is);
		sendFile(fileName);
	}
	
	//得到http请求要访问的资源名称
	public String parse(InputStream is){
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String fileName = null;
		try {
			String header = br.readLine();
			if(header != null && !"".equals(header)){
				String[] content = header.split(" ");
				if(content.length != 3){
					sendErrorMessage(400, "Brower query error ");
					return null;
				}
				fileName = content[1];
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	//发送错误信息
	public void sendErrorMessage(int errorCode, String errorMessage){
		out.println("HTTP/1.1" + errorCode +" " +errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode:"+errorCode+",Message:"+errorMessage+"</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}
	
	//发送请求文件
	public void sendFile(String fileName){
		if(fileName == null || "".equals(fileName)){
			return;
		}
		FileInputStream fis = null;
		File file = new File(WEB_ROOT,fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File not found!");
			return;
		}
		try {
			fis = new FileInputStream(file);
			
			out.println("HTTP/1.1 200 queryfile");
			out.println("content-type: text/html");
			out.println("content-length:"+file.length());
			out.println();
			byte[] buffer = new byte[BUFFER_SIZE];
			while( (fis.read(buffer, 0, BUFFER_SIZE)) != -1){
				out.write(buffer, 0, BUFFER_SIZE);
			}
			out.flush();
			out.close();
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
		
	} 
}
